/**
 * 角色加载器
 * 专门用于在3DGS场景中加载和管理GLB角色模型
 */

import { THREE, GLTFLoader } from '../core/three-singleton.js';

export class CharacterLoader {
    constructor(options = {}) {
        this.options = {
            enableAnimations: options.enableAnimations !== false,
            enableShadows: options.enableShadows !== false,
            optimizeForVR: options.optimizeForVR !== false,
            ...options
        };
        
        this.gltfLoader = new GLTFLoader();
        this.loadedCharacters = new Map();
        this.animationMixers = new Map();
    }
    
    /**
     * 加载GLB角色模型
     */
    async loadCharacter(modelPath, options = {}) {
        try {
            console.log('开始加载角色模型:', modelPath);
            
            const loadOptions = {
                ...this.options,
                ...options
            };
            
            // 检查是否已经加载过
            if (this.loadedCharacters.has(modelPath)) {
                console.log('角色模型已缓存，克隆现有模型');
                return this.cloneCharacter(modelPath);
            }
            
            // 加载GLTF模型
            const gltf = await this.loadGLTF(modelPath);
            const character = await this.processCharacter(gltf, loadOptions);
            
            // 缓存角色
            this.loadedCharacters.set(modelPath, {
                gltf: gltf,
                character: character,
                animations: gltf.animations || []
            });
            
            console.log('角色模型加载完成:', modelPath);
            return character;
            
        } catch (error) {
            console.error('角色加载失败:', error);
            return this.createPlaceholderCharacter();
        }
    }
    
    /**
     * 加载GLTF文件
     */
    loadGLTF(modelPath) {
        return new Promise((resolve, reject) => {
            this.gltfLoader.load(
                modelPath,
                (gltf) => resolve(gltf),
                (progress) => {
                    const percent = (progress.loaded / progress.total) * 100;
                    console.log(`角色加载进度: ${percent.toFixed(1)}%`);
                },
                (error) => reject(error)
            );
        });
    }
    
    /**
     * 处理角色模型
     */
    async processCharacter(gltf, options) {
        const character = gltf.scene.clone();
        character.name = 'Character';
        
        // 设置角色属性
        this.setupCharacterProperties(character, options);
        
        // 优化材质
        this.optimizeCharacterMaterials(character, options);
        
        // 设置阴影
        if (options.enableShadows) {
            this.setupCharacterShadows(character);
        }
        
        // 设置动画
        if (options.enableAnimations && gltf.animations.length > 0) {
            this.setupCharacterAnimations(character, gltf.animations);
        }
        
        // VR优化
        if (options.optimizeForVR) {
            this.optimizeCharacterForVR(character);
        }
        
        return character;
    }
    
    /**
     * 设置角色属性
     */
    setupCharacterProperties(character, options) {
        // 设置默认位置和缩放
        character.position.set(0, 0, 0);
        character.scale.setScalar(options.scale || 1.0);
        
        // 设置用户数据
        character.userData = {
            isCharacter: true,
            characterType: options.characterType || 'default',
            loadTime: Date.now(),
            ...options.userData
        };
        
        // 确保角色可见
        character.visible = true;
        character.frustumCulled = true;
    }
    
    /**
     * 优化角色材质
     */
    optimizeCharacterMaterials(character, options) {
        character.traverse((child) => {
            if (child.isMesh && child.material) {
                const material = child.material;
                
                // 启用顶点颜色
                if (material.vertexColors === undefined) {
                    material.vertexColors = false;
                }
                
                // 优化透明度
                if (material.transparent) {
                    material.alphaTest = 0.1;
                }
                
                // VR优化
                if (options.optimizeForVR) {
                    // 降低材质复杂度
                    if (material.roughnessMap) {
                        material.roughness = 0.8;
                    }
                    if (material.metalnessMap) {
                        material.metalness = 0.1;
                    }
                }
                
                // 确保材质更新
                material.needsUpdate = true;
            }
        });
    }
    
    /**
     * 设置角色阴影
     */
    setupCharacterShadows(character) {
        character.traverse((child) => {
            if (child.isMesh) {
                child.castShadow = true;
                child.receiveShadow = true;
            }
        });
    }
    
    /**
     * 设置角色动画
     */
    setupCharacterAnimations(character, animations) {
        if (animations.length === 0) return;
        
        const mixer = new THREE.AnimationMixer(character);
        const actions = {};
        
        animations.forEach((clip) => {
            const action = mixer.clipAction(clip);
            actions[clip.name] = action;
        });
        
        // 存储动画信息
        character.userData.animations = actions;
        character.userData.mixer = mixer;
        
        // 缓存mixer
        this.animationMixers.set(character.uuid, mixer);
        
        console.log(`设置了 ${animations.length} 个动画:`, Object.keys(actions));
    }
    
    /**
     * VR优化
     */
    optimizeCharacterForVR(character) {
        character.traverse((child) => {
            if (child.isMesh) {
                // 简化几何体
                if (child.geometry.attributes.position.count > 10000) {
                    console.log('简化高多边形网格:', child.name);
                    // 这里可以添加几何体简化逻辑
                }
                
                // 优化材质
                if (child.material) {
                    child.material.precision = 'mediump';
                }
            }
        });
    }
    
    /**
     * 克隆角色
     */
    cloneCharacter(modelPath) {
        const cached = this.loadedCharacters.get(modelPath);
        if (!cached) return null;
        
        const clonedCharacter = cached.character.clone();
        
        // 重新设置动画
        if (cached.animations.length > 0) {
            this.setupCharacterAnimations(clonedCharacter, cached.animations);
        }
        
        return clonedCharacter;
    }
    
    /**
     * 创建占位符角色
     */
    createPlaceholderCharacter() {
        const geometry = new THREE.CapsuleGeometry(0.5, 1.8, 4, 8);
        const material = new THREE.MeshLambertMaterial({ 
            color: 0x4a90e2,
            transparent: true,
            opacity: 0.8
        });
        
        const character = new THREE.Mesh(geometry, material);
        character.name = 'PlaceholderCharacter';
        character.userData = {
            isCharacter: true,
            isPlaceholder: true
        };
        
        return character;
    }
    
    /**
     * 播放角色动画
     */
    playAnimation(character, animationName, options = {}) {
        const animations = character.userData.animations;
        const mixer = character.userData.mixer;
        
        if (!animations || !mixer || !animations[animationName]) {
            console.warn('动画不存在:', animationName);
            return null;
        }
        
        // 停止当前动画
        Object.values(animations).forEach(action => action.stop());
        
        // 播放新动画
        const action = animations[animationName];
        action.reset();
        action.setLoop(options.loop !== false ? THREE.LoopRepeat : THREE.LoopOnce);
        action.play();
        
        console.log('播放动画:', animationName);
        return action;
    }
    
    /**
     * 停止角色动画
     */
    stopAnimation(character, animationName = null) {
        const animations = character.userData.animations;
        
        if (!animations) return;
        
        if (animationName && animations[animationName]) {
            animations[animationName].stop();
        } else {
            // 停止所有动画
            Object.values(animations).forEach(action => action.stop());
        }
    }
    
    /**
     * 更新动画
     */
    updateAnimations(deltaTime) {
        this.animationMixers.forEach((mixer) => {
            mixer.update(deltaTime);
        });
    }
    
    /**
     * 定位角色到3DGS场景中
     */
    positionCharacterInSplatScene(character, splatMesh, options = {}) {
        if (!character || !splatMesh) return;
        
        // 获取3DGS场景的边界
        const box = new THREE.Box3().setFromObject(splatMesh);
        const center = box.getCenter(new THREE.Vector3());
        const size = box.getSize(new THREE.Vector3());
        
        // 设置角色位置
        const spawnPoint = options.spawnPoint || { x: 0, y: 0, z: -2 };
        character.position.set(
            center.x + spawnPoint.x,
            box.min.y + (character.userData.characterHeight || 1.8),
            center.z + spawnPoint.z
        );
        
        // 让角色面向场景中心
        character.lookAt(center.x, character.position.y, center.z);
        
        console.log('角色已定位到3DGS场景中:', character.position);
    }
    
    /**
     * 清理资源
     */
    dispose() {
        // 清理动画混合器
        this.animationMixers.forEach((mixer) => {
            mixer.stopAllAction();
        });
        this.animationMixers.clear();
        
        // 清理缓存的角色
        this.loadedCharacters.forEach((cached) => {
            if (cached.character.geometry) {
                cached.character.geometry.dispose();
            }
            if (cached.character.material) {
                if (Array.isArray(cached.character.material)) {
                    cached.character.material.forEach(mat => mat.dispose());
                } else {
                    cached.character.material.dispose();
                }
            }
        });
        this.loadedCharacters.clear();
    }
}

// 导出单例实例
export const characterLoader = new CharacterLoader();